package com.block.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.enums.ChargeTypeEnum;
import com.block.common.model.dto.CountInfoDTO;
import com.block.common.model.dto.MemberBaseInfoDTO;
import com.block.common.service.IChannelCommonService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.ChannelBaseInfo;
import com.block.db.entity.ProductBaseInfo;
import com.block.db.entity.ProductOnlieInfo;
import com.block.db.mapper.ProductOnlieInfoMapper;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.model.vo.ProductInfoVO;
import com.block.product.service.IProductBaseInfoService;
import com.block.product.service.IProductOnlieInfoService;
import com.block.product.service.IProductUnionLoginService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 产品上线信息 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-09-02
 */
@Service
public class ProductOnlieInfoServiceImpl extends ServiceImpl<ProductOnlieInfoMapper, ProductOnlieInfo> implements IProductOnlieInfoService {

    private static final Logger log = LogFactory.getProductLog();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    IProductBaseInfoService productBaseInfoService;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IProductUnionLoginService productUnionLoginService;
    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public ResponseVo  prodInfoList(ChannelBaseInfo channelBaseInfo, String sceneId, Long uid, String reqIp) {

        String nowDate = LocalDate.now().toString();
        String nowTime = LocalDateUtil.getNowDateStr(LocalDateUtil.SIMPLE_TIME);

        //
        MemberBaseInfoDTO memberBaseInfoDTO = memberCommonService.getMemberBaseInfo(uid);
        if (ObjectUtil.isNotEmpty(memberBaseInfoDTO) &&
                ObjectUtil.isNotEmpty(memberBaseInfoDTO.getShowProdTime()) &&
                LocalDateTime.now().isBefore(memberBaseInfoDTO.getShowProdTime())){
            // 用户信息不为空，且产品展示时间不为空，且当前时间在产品展示时间之前（不展示用户产品）
            // 直接返回成功
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataList", new ArrayList<>());
            return new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
        }


        if (!ObjectUtil.equals(Integer.valueOf(1), channelBaseInfo.getShowProductFlag())){
            // 不展示产品列表的时候，返回空几个
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataList", new ArrayList<>());
            return new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
        }

        String channelCode = channelBaseInfo.getChannelCode();


        // 查询已经上线的产品
        List<ProductOnlieInfo> onlieInfoList = this.baseMapper.getOnlineProductInfoList(sceneId,channelBaseInfo.getChannelType(), nowDate, nowTime);

        List<ProductInfoVO> dataList = new ArrayList<>();
        for (ProductOnlieInfo productOnlieInfo : onlieInfoList) {

            String outChannelArray = productOnlieInfo.getOutChannelArray();
            String inChannelArray = productOnlieInfo.getInChannelArray();

            // 检查不允许推送的渠道（outChannelArray）
            List<String> outChannelList = JSON.parseArray(outChannelArray, String.class);
            if (CollUtil.isNotEmpty(outChannelList) && outChannelList.contains(channelCode)) {
                continue;
            }

            // 检查允许推送的渠道（inChannelArray）
            List<String> inChannelList = JSON.parseArray(inChannelArray, String.class);
            if (CollUtil.isNotEmpty(inChannelList) && !inChannelList.contains(channelCode)) {
                continue;
            }

            // 2023/9/2 uv 控量 ，查询是否展示
            String redisKey = StrUtil.format(RedisKeyConstant.PRODUCT_UV_REMAIN_COUNT_KEY, nowDate, productOnlieInfo.getProductId());
            String remainNumber = stringRedisTemplate.opsForValue().get(redisKey);
            if (ObjectUtil.isNotEmpty(remainNumber) && Integer.valueOf(remainNumber) <= 0){
                continue;
            }

            // 查询产品基本信息
            ProductBaseInfo productInfo = productBaseInfoService.getProductInfoById(productOnlieInfo.getProductId());

            ProductInfoVO productInfoVO = new ProductInfoVO();
            productInfoVO.setProductId(String.valueOf(productInfo.getId()));
            productInfoVO.setProductName(productInfo.getProductName());
            productInfoVO.setProductLogo(productInfo.getLogoUrl());
            productInfoVO.setProductTitle(productInfo.getTitleInfo());
            productInfoVO.setProductLabel(productInfo.getLabelInfo());
            productInfoVO.setShowFlag(productInfo.getShowFlag());
            productInfoVO.setDownloadFlag(productInfo.getDownloadFlag());
            productInfoVO.setMaxAmount(productInfo.getMaxAmount());
            productInfoVO.setRateAmountInfo(StrUtil.format("{}~{}%", productInfo.getMinRate(), productInfo.getMaxRate()));

            boolean unionFlag = ObjectUtil.equals(productInfo.getChargeType(), ChargeTypeEnum.UNION.getValue());
            productInfoVO.setUnionFlag(unionFlag);
            if (unionFlag){
                // 2023/9/2 联登获取 产品信息
                //  用户进行撞库，确认是否显示。或者直接获取到缓存的产品信息（产品登陆信息）
                UnionLoginResult loginResult = productUnionLoginService.getUnionProductShowInfo(productInfo, uid);
                log.info("【产品列表】产品联登【productId】{}【uid】{}【result】{}", productInfo.getId(), uid, JSON.toJSONString(loginResult));
                if (loginResult.isSuccess()){

                    String loginUrl = loginResult.getLoginUrl();
                    if(StrUtil.isNotEmpty(loginUrl)){
                        productInfoVO.setDetailUrl(loginResult.getLoginUrl());
                    }else {
                        productInfoVO.setDetailUrl("");
                    }
                    dataList.add(productInfoVO);
                }
            }else{
                productInfoVO.setDetailUrl(productInfo.getDetailUrl());
                // 非联登产品，直接添加显示
                dataList.add(productInfoVO);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataList", dataList);

        // 消息通知
        if (StrUtil.equals(sceneId, "1")){
            countProdListUv(channelBaseInfo.getChannelCode(), reqIp);
        }

        return new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
    }

    /**
     * 基于渠道统计，每个产品列表的uv
     * @param channelCode
     * @param reqIp
     */
    public void countProdListUv(String channelCode, String reqIp){

        Long remainSecond = LocalDateUtil.getRemainSecondNumber();
        String redisKey = StrUtil.format(RedisKeyConstant.PROD_LIST_UV_KEY, channelCode, reqIp);
        boolean result = stringRedisTemplate.opsForValue()
                .setIfAbsent(redisKey, System.currentTimeMillis()+"", remainSecond, TimeUnit.SECONDS);

        if (result){
            CountInfoDTO countInfoDTO = new CountInfoDTO(channelCode);
            countInfoDTO.setUvProdList(1);

            channelCommonService.updateChannelCount(countInfoDTO);
        }
    }
}
